<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload" @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="客户:">
              <el-input v-model="where.keyword" clearable placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:customer:index')" class="ele-btn-icon" icon="el-icon-search" type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where" height="calc(100vh - 315px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button v-if="permission.includes('sys:customer:add')" class="ele-btn-icon" icon="el-icon-plus" size="small" type="primary" @click="openEdit(null)">
            新建客户
          </el-button>
          <el-button v-if="permission.includes('sys:customer:delete')"  :disabled="!selection.length" class="ele-btn-icon" icon="el-icon-delete" size="small" type="primary" @click="deleteCustomer">
            批量删除
          </el-button>

         <div class="exportBtn" v-if="permission.includes('sys:customer:export')">
           <download-excel
             class="export-excel-wrapper"
             :data="selection"
             :fields="json_fields"
             :before-generate="startDownload"
             :before-finish="finishDownload"
             :header="title"
             name="客户.xls"
           >
             <el-button size="small" type="primary"  :disabled="!selection.length&&!exportFlag" :loading="exportFlag">导出</el-button>
           </download-excel>
         </div>

          <div class="exportBtn">
          <el-button v-if="permission.includes('sys:customer:export')" type="primary" class="ele-btn-icon" size="small" @click="exportAll" :loading="exportAllLoading">
            导出全部
          </el-button>
          </div>
          <div class="exportBtn">
            <el-button icon="el-icon-download" type="primary"
                       class="ele-btn-icon" size="small" @click="downloadModel">
              下载模板
            </el-button>
          </div>
          <div class="exportBtn">
            <el-button icon="el-icon-upload2" v-if="permission.includes('sys:customer:import')" type="primary" class="ele-btn-icon" size="small" @click="importAll">
              导入
            </el-button>
          </div>

        </template>

        <!-- 所在区域-->
        <template slot="area" slot-scope="{row}">
          <span>{{ row.province_name }} {{ row.city_name }}  {{ row.county_name }}</span>
        </template>
        <!--客户编号-->
        <template slot="customerNumber" slot-scope="{row}">
          <span style="color: rgb(37, 99, 235);cursor: pointer" @click="toDetail(row.id)">
            {{ row.customer_number }}
          </span>
        </template>
        <!--联系人-->
        <template slot="user_name" slot-scope="{row}">
          <span v-if="row.user">{{ row.user.name }}</span>
          <span v-else style="color: red"> 暂无默认联系人</span>
        </template>
        <!--联系电话-->
        <template slot="user_phone" slot-scope="{row}">
          <span v-if="row.user">{{ row.user.phone }}</span>
          <span v-else style="color: red">暂无默认联系人电话</span>
        </template>
        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-link v-if="permission.includes('sys:customer:edit')" :underline="false" icon="el-icon-edit" type="primary"
                   @click="openEdit(row)">
            修改
          </el-link>
          <el-popconfirm class="ele-action" title="确定要删除此客户吗？" @confirm="remove(row)">
            <el-link v-show="permission.includes('sys:customer:delete')" slot="reference" :underline="false"
                     icon="el-icon-delete" type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!--弹窗新增-->
    <add-customer :data="current" :visible.sync="showEdit" @done="reset"  ref="AddCustomer"/>
<!--导入弹窗-->
    <importData :visible.sync="showImport" @done="completeImport" type="customer"></importData>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import AddCustomer from "@/views/customer/customer/components/AddCustomer.vue";
import importData from "@/components/importData.vue";

export default {
  components: {
    AddCustomer,
    importData
  },
  name: 'SystemLevel',
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      showImport:false,
      title:"客户信息",
      json_fields: {
        "客户编号":'customer_number',
        "客户名称":'name',
        "客户简称":'short_name',
        "联系人":'user.name',
        "电话":'user.phone',
        "地址":'detail_address',
        "邮箱":'user.email',
        "客户行业":'entry_type_name',
        "签约日期":'contact_at',
        "服务部门":'department_name',
        "客户负责人":'owner_name',
        "创建人":'create_user.realname',
        "创建时间":'create_time',
        "备注信息":'remark',
      },
      // 表格数据接口
      url: '/customers',
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left",
          emptyText: '暂无',

        },
        {
          prop: 'customer_number',
          label: '客户编号',
          width: 200,
          align: 'center',
          showOverflowTooltip: true,
          slot: "customerNumber",
          emptyText: '暂无',
        },
        {
          prop: 'name',
          label: '客户名称',
          showOverflowTooltip: true,
          minWidth: 200,
          emptyText: '暂无',
          align: 'center',
        },
        {
          prop: 'user?.name',
          label: '联系人',
          align: 'center',
          width: 150,
          resizable: false,
          emptyText: '暂无',
          slot: 'user_name',
        },
        {
          prop: 'user?.phone',
          label: '联系电话',
          align: 'center',
          showOverflowTooltip: true,
          width: 150,
          emptyText: '暂无',
          slot: 'user_phone',
        },
        {
          prop: 'tag_name',
          label: '客户标签',
          showOverflowTooltip: true,
          minWidth: 160,
          emptyText: '暂无',
          align: 'center'
        },
        {
          columnKey: 'area',
          label: '区域',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
          emptyText: '暂无',
          slot: 'area',
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          emptyText: '暂无',
          fixed: "right"
        },
        {
          prop: 'address',
          label: '详细地址',
          align: 'center',
          showOverflowTooltip: true,
          emptyText: '暂无',
          width: 150
        },
        // {
        //   prop: 'department_name',
        //   label: '服务网点',
        //   align: 'center',
        //   showOverflowTooltip: true,
        //   emptyText: '暂无',
        //   width: 100
        // },
        {
          prop: 'owner_name',
          label: '客户负责人',
          emptyText: '暂无',
          align: 'center',
          showOverflowTooltip: true,
          width: 150
        },
        {
          prop: 'create_user.realname',
          label: '创建人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'create_time_format',
          label: '创建时间',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      exportAllLoading:false,
      exportFlag:false,
      model:'#',
    };
  },
  mounted() {
    this.getModel()
  },
  methods: {
    getModel() {
      this.$http.get('/template/customer').then((res) => {
        this.model = res.data.data
        //聚焦刷新
        this.$forceUpdate()
      })

    },
    downloadModel() {
      window.open(this.model, '_self');
    },
    startDownload(){
      this.exportFlag=true
    },
    finishDownload(){
      this.exportFlag=false
    },
    /*导入*/
    importAll(){

      this.showImport=true
    },
    completeImport(){
      this.showImport=false
      this.reload()
    },
    /*导出全部*/
    exportAll(){
      this.exportAllLoading=true
      this.$http.get('customers_export').then(res => {
        if (res.data.code === 0) {
          this.exportAllLoading=false
          this.$message.success(res.data.msg);
          const link = document.createElement('a')
          link.href = res.data.data.url
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } else {
          this.exportAllLoading=false
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    //进入详情页面
    toDetail(e) {
      this.$router.push({
        path: "/customer/customer/info",
        query: { id: e }
      })
    },
    /* 刷新表格 */
    reload() {
      this.$refs.table.reload({ where: this.where });
    },
    /* 重置搜索 */
    reset() {
      this.current = {}
      this.where = {};
      this.reload();
    },
    /* 显示编辑 */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 删除 */
    remove(row) {

      this.$http.delete('/customers/' + row.id).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    // 批量删除
    deleteCustomer() {
      let temp = (this.selection.map(item => {
        return item.id
      })).join(',')
      if (temp === "") {
        return this.$message({ type: 'error', message: "请先选择要删除的数据" });
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/customers", { params: { ids: temp } }).then(res => {
          this.$message({ type: 'success', message: res.data.msg });
          this.reload();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .exportBtn{
    margin-left: 10px;
  }
</style>
